
var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : 'root',
  database : 'tijian'
});
connection.connect();
var datas={"code":0,"data":'',"msg":''};
exports.login=function(user,callback){
 var sql="SELECT * from user_info where name='"+user.name+"' and password='"+user.password+"'";
  connection.query(sql,function (err, result) {
    if(err){
      datas.msg=err.message;
      callback(result)
    }else{
        localStorage.setItem("isLogin","1");
        localStorage.setItem("user",JSON.stringify(result[0]));
      callback(result[0])
    }
  });
};


exports.find = function (callback) {
	connection.query('SELECT * from orders', function (error, results, fields) {
	  if (error) throw error;
	  callback(null, results)
	});
}

exports.saveOrder = function (order,callback) {
    var user=localStorage.getItem("user");
    user =JSON.parse(user);
    var sql="INSERT INTO `orders`(`name`, `producId`, `price`, `userId`, `userName`) VALUES (?, ?, ?, ?, ?);";
    var  addSqlParams = [order.name, order.id,order.price,user.id,user.name];
    connection.query(sql,addSqlParams,function (err,results) {
        callback(null);
    })
}


exports.findById = function (id, callback) {
  connection.query("SELECT * from user_info where id="+id, function (error, results, fields){
    callback(null, results[0])
  })
}

exports.save = function (user, callback) {
  var sql="INSERT INTO user_info( `name`, `password`,phone,nickName) VALUES (?,?,?,?)";
  var  addSqlParams = [user.name, user.password,user.phone,user.nickName];
  connection.query(sql,addSqlParams,function (err,results) {
    callback(null);
  })
}

/**
 * 更新
 */
exports.updateById = function (user, callback) {
 var sql='UPDATE user_info set phone=? ,name=?,password=? where id=?';
  var  para = [user.phone,user.name, user.password,user.id];
  connection.query(sql,para,function (err,results) {
    callback(null);
  })
}

/**
 * 删除
 */
exports.deleteById = function (id, callback) {
  var sql="DELETE from orders where id="+id;
  console.log(sql);
  connection.query(sql,function (err,result) {
    callback(null);
  })
}
